package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentService;

import com.netflix.appinfo.InstanceInfo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
/**
 * slf4j注解用于开启日志
 * 处理查询和新增请求
 */
public class PaymentController {
    @Autowired
    PaymentService paymentService;
    @Value("${server.port}")
    String serverPort;
    @PostMapping(value = "/payment/create")
    public CommonResult create(@RequestBody Payment payment) {
        //调用插入方法 返回值大于0 成功 否则失败
        int result = paymentService.create(payment);

        //开启日志
        log.info("插入结果：" + result);
        if (result > 0) {
            return new CommonResult(200, "数据插入成功:serverPort:"+serverPort, result);
        } else {
            return new CommonResult(444, "数据插入失败:serverPort:"+serverPort, null);
        }

    }

    @GetMapping(value = "/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable(value = "id") Long id) {

        //调用插入方法 返回值大于0 成功 否则失败
        Payment payment = paymentService.getPaymentById(id);
        //开启日志
        log.info("查询结果：" + payment);

        if (payment != null) {
            return new CommonResult(200, "数据查询成功:serverPort:"+serverPort, payment);
        } else {
            return new CommonResult(444, "没有对应记录,id:" + id, null);
        }

    }
//    返回服务相关信息
//    EnableDiscoverClient注解
//    包含所有up服务
//    包括服务名称 服务id 服务主机 服务端口 实例id 服务uri
    @Autowired
    DiscoveryClient discoveryClient;
    @GetMapping(value = "/getDiscovery")
    public DiscoveryClient getDiscovery() {
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info(service);
        }
        List<ServiceInstance> list = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : list) {
            log.info("主机:"+instance.getHost()+"端口:"+instance.getPort()+"uri:"+instance.getUri()+"实例id:"+instance.getInstanceId()+"服务id:"+instance.getServiceId());
        }
        return discoveryClient;
    }

}
